//
//  XYJXCResultViewController.m
//  徙游记-01
//
//  Created by hcios on 2017/7/12.
//  Copyright © 2017年 鹿林. All rights reserved.
//

#import "XYJXCResultViewController.h"
#import "XYJXCResultModel.h"
#import "XYJXCResultFrameModel.h"
#import "XYJXCTableViewCell.h"

#import "XYJXCResultHeaderView.h"
#import "UIImageView+WebCache.h"
#import "XLPhotoBrowser.h"
#import "UIView+XLExtension.h"

//分享
#import <UMSocialCore/UMSocialCore.h>
#import <UShareUI/UShareUI.h>
#import "ZYShareItem.h"
#import "ZYShareView.h"

//跳转
#import "XYJLXResultViewController.h"
#import "YJResultAddTableViewCell.h"



@interface XYJXCResultViewController ()<UITableViewDelegate,UITableViewDataSource,XYJXCTableViewCellDelegate,XLPhotoBrowserDatasource,XLPhotoBrowserDelegate>{
    UITableView *_tableView;
    NSMutableArray *_dataSectionArr;
    UIButton *addButton;
    UITableView *_addTableView;
    
    NSString *imageUrl;
    NSString *name;
    
    NSIndexPath *_indexPath;
    
    NSMutableArray *_dataUrlArray;
    
    NSMutableArray *_dataImageViewArray;
    
    NSMutableArray *_dataUrlArrSection;
    
    
    UIButton *topButton;
    UIButton *returnButton;
    UIButton *shareButton;
    
    XYJXCResultHeaderView *headerView;
}

@end

@implementation XYJXCResultViewController

-(instancetype)init{
    if (self = [super init]) {
        _dataSectionArr = [[NSMutableArray alloc] init];
        _indexPath = [[NSIndexPath alloc] init];
        _dataUrlArray = [[NSMutableArray alloc] init];
        _dataImageViewArray = [[NSMutableArray alloc] init];
        _dataUrlArrSection = [[NSMutableArray alloc] init];
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBarHidden = YES;
    self.tabBarController.tabBar.hidden = YES;
}


- (void)viewDidLoad {
    [super viewDidLoad];
 
    self.automaticallyAdjustsScrollViewInsets = NO;

    [self setupSubViews];
    [self netWorking];
}


-(void)setupSubViews{
    
    //tableView
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.showsVerticalScrollIndicator = YES;
    [self.view addSubview:_tableView];

    
    //addButton
    addButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [addButton setFrame:CGRectMake(10, SCREEN_HEIGHT - 100, 50, 50)];
    addButton.layer.cornerRadius = 25;
    addButton.layer.masksToBounds = YES;
    addButton.backgroundColor = [UIColor whiteColor];
    [addButton addTarget:self action:@selector(clickAdd) forControlEvents:UIControlEventTouchUpInside];
    [addButton setImage:[UIImage imageNamed:@"resultAdd"] forState:UIControlStateNormal];
    [addButton.titleLabel setFont:[UIFont systemFontOfSize:11]];
    [self.view addSubview:addButton];
    [self.view bringSubviewToFront:addButton];
    
    
    //topButton
    topButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [topButton setFrame:RECT_MAKE(SCREEN_WIDTH - 60, SCREEN_HEIGHT - 100, 50, 50)];
    topButton.layer.cornerRadius = 25;
    topButton.layer.masksToBounds = YES;
    [topButton addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
    [topButton setImage:[UIImage imageNamed:@"back_top"] forState:UIControlStateNormal];
    [topButton.titleLabel setFont:[UIFont systemFontOfSize:11]];
    topButton.hidden = YES;
    [self.view addSubview:topButton];
    [topButton bringSubviewToFront:_tableView];
    
    //returnButton
    returnButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [returnButton setFrame:RECT_MAKE(10, 20, 50, 50)];
    returnButton.layer.cornerRadius = 25;
    returnButton.layer.masksToBounds = YES;
    returnButton.alpha = 0.618;
    returnButton.backgroundColor = [UIColor blackColor];
    [returnButton setImage:[UIImage imageNamed:@"homepage_back_icon03"] forState:UIControlStateNormal];
    [returnButton addTarget:self action:@selector(returnBack) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:returnButton];
    [self.view bringSubviewToFront:returnButton];
    
    
    //shareButton
    shareButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [shareButton setFrame:RECT_MAKE(SCREEN_WIDTH - 60, 20, 50, 50)];
    shareButton.layer.cornerRadius = 25;
    shareButton.layer.masksToBounds = YES;
    shareButton.alpha = 0.618;
    shareButton.backgroundColor = [UIColor blackColor];
    [shareButton setImage:[UIImage imageNamed:@"homepage_message_icon03"] forState:UIControlStateNormal];
    [shareButton addTarget:self action:@selector(share) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:shareButton];
    [self.view bringSubviewToFront:shareButton];
    
    
    //addTableView
    _addTableView = [[UITableView alloc] initWithFrame:RECT_MAKE(-screen_half_width, 0, screen_half_width, SCREEN_HEIGHT) style:UITableViewStyleGrouped];
    _addTableView.delegate = self;
    _addTableView.dataSource = self;
    _addTableView.showsVerticalScrollIndicator = NO;
    _addTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _addTableView.layer.borderWidth = 1;
    _addTableView.layer.backgroundColor = [UIColor blackColor].CGColor;
    
}

#pragma mark - 按钮点击事件
//分享
- (void)share{
    __weak typeof(self) weakSelf = self;
    ZYShareItem *itemWeiXin = [ZYShareItem itemWithTitle:@"微信好友" icon:@"wechat-icon" handler:^{
        [weakSelf shareWebToWechat];
        NSLog(@"分享");
    }];
    
    NSArray *arr = @[itemWeiXin];
    ZYShareView *share = [ZYShareView shareViewWithShareItems:arr functionItems:nil];
    [share show];
}

//返回
- (void) returnBack{
    
    NSLog(@"点击");
    [[self navigationController]popViewControllerAnimated:YES];
}

//返回顶部
- (void)click{
    [_tableView setContentOffset:CGPointMake(0, 0) animated:YES];
    topButton.hidden = YES;
}


//添加侧边栏
-(void)clickAdd{
    NSLog(@"点击");
    [self.view addSubview:_addTableView];
    [UIView animateWithDuration:0.7 animations:^{
        _addTableView.frame = RECT_MAKE(0, 0, screen_half_width, SCREEN_HEIGHT);
    }];
}


#pragma mark - tableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if ([tableView isEqual:_tableView]) {
        NSInteger count = [_dataSectionArr[section] count];
        return count;
    }else{
        NSInteger count = [_dataSectionArr[section] count];
        return count;
    }
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if ([tableView isEqual:_tableView]) {
        XYJXCTableViewCell *cell = [XYJXCTableViewCell cellWithTableView:tableView];
        cell.frameModel = _dataSectionArr[indexPath.section][indexPath.row];
        cell.delegate = self;
        return cell;
    }else{
        NSString *cellID = [NSString stringWithFormat:@"cellID%ld%ld",(long)[indexPath section],(long)[indexPath row]];
        YJResultAddTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (!cell) {
            cell = [[YJResultAddTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
            XYJXCResultFrameModel *frameModel = _dataSectionArr[indexPath.section][indexPath.row];
            if ([frameModel.model.xc_plan_days_entry_name isEqualToString:@""]) {
                [cell layoutWithCellArray:@"今日备忘"];
            }else{
                [cell layoutWithCellArray:frameModel.model.xc_plan_days_entry_name];
            }
        }
        return cell;
    }
}



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if ([tableView isEqual:_tableView]) {
        return _dataSectionArr.count;
    }else{
        return _dataSectionArr.count;
    }
}



#pragma mark - tableViewDelegate
//点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSLog(@"%ld%ld",(long)[indexPath section],(long)[indexPath row]);
    
    if ([tableView isEqual:_tableView]) {
        [_addTableView removeFromSuperview];
    }
    if ([tableView isEqual:_addTableView]) {
        //计算出右侧tableView将要滚动的位置
        NSIndexPath *moveIndexPath = [NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section];
        //将右侧tableView移动到指定位置
        [_tableView selectRowAtIndexPath:moveIndexPath animated:YES scrollPosition:UITableViewScrollPositionTop];
        //取消选中效果
        [_tableView deselectRowAtIndexPath:moveIndexPath animated:YES];
        [_addTableView removeFromSuperview];
    }
}

//cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if ([tableView isEqual:_tableView]) {
        XYJXCResultFrameModel * frameModel = _dataSectionArr[indexPath.section][indexPath.row];
        
        return frameModel.cellHeight;
    }else{
        return 40;
    }
}

//Header
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if ([tableView isEqual:_tableView]) {
        if (section == 0) {
            headerView = [[XYJXCResultHeaderView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 210)];
            [headerView.backImgView sd_setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:[UIImage imageNamed:@"zhanWeiTu"]];
            headerView.nameLab.text = name;
            headerView.dayLab.text = [NSString stringWithFormat:@"%@天 / %@个旅行地",_days_count,_nodes_count];
            //实现下拉放大
            headerView.backImgView.contentMode = UIViewContentModeScaleAspectFill;
            return headerView;
            
        }else{
            UIView *headerLab = [[UIView alloc] initWithFrame:RECT_MAKE(0, 0, SCREEN_WIDTH, 20)];
            headerLab.backgroundColor = [UIColor cyanColor];
            return headerLab;
        }
    }else{
        return nil;
    }
}


//Header高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if ([tableView isEqual:_tableView]) {
        if (section == 0) {
            return 210;
        }else return 20;
    }else{
        if (section == 0) {
            return 20;
        }else return CGFLOAT_MIN;
    }
}


//footer高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return CGFLOAT_MIN;
}


#pragma mark - 网络请求
-(void)netWorking{
    
    NSString *urlString = [NSString stringWithFormat:@"http://chanyouji.com/api/plans/%@.json",_selfID];
    NSDictionary *param = @{@"page":@"1"};
    [[SeverceHttpRequest sharedManager] GET:urlString parameters:param success:^(id reponseObject) {
        
        imageUrl = reponseObject[@"image_url"];
        name = reponseObject[@"name"];
        
        //遍历section
        for (NSDictionary *dict1 in reponseObject[@"plan_days"]) {
            NSMutableDictionary *resultDict = [[NSMutableDictionary alloc] initWithDictionary:dict1];
            NSMutableArray *rowArray = [[NSMutableArray alloc] init];
            
            //取出memo
            XYJXCResultModel *model1 = [[XYJXCResultModel alloc] initWithMemoDict:dict1];
            XYJXCResultFrameModel *frameModel = [[XYJXCResultFrameModel alloc] init];
            frameModel.model = model1;
            [rowArray addObject:frameModel];
            
            //数组储存每个section的row(图片的url)
            NSMutableArray *urlArr = [[NSMutableArray alloc] init];
            //图片
            NSMutableArray *imageViewArr = [[NSMutableArray alloc] init];
            //遍历row
            for (NSDictionary *dict2 in resultDict[@"plan_nodes"]) {
                //取出剩下的dict
                XYJXCResultModel *model2 = [[XYJXCResultModel alloc] initWithPlanDict:dict2];
                XYJXCResultFrameModel *frameModel2 = [[XYJXCResultFrameModel alloc] init];
                frameModel2.model = model2;
                [rowArray addObject:frameModel2];
                [_dataUrlArray addObject:model2.xc_plan_days_image_url];
                [urlArr addObject:model2.xc_plan_days_image_url];
                
                //图片
                UIImageView *imageView = [[UIImageView alloc] init];
                [imageView sd_setImageWithURL:[NSURL URLWithString:model2.xc_plan_days_image_url]];
                [imageViewArr addObject:imageView];
            }
            [_dataImageViewArray addObject:imageViewArr];
            [_dataUrlArrSection addObject:urlArr];
            [_dataSectionArr addObject:rowArray];
            
        }
        [_tableView reloadData];
        
    } failure:^(NSError *error) {
        
        NSLog(@"网络请求失败");
    }];
}


#pragma mark - ScrollView
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGPoint point = scrollView.contentOffset;
    if (point.y < 0) {
        CGRect rect = headerView.backImgView.frame;
        rect.origin.y = point.y;
        rect.size.height = -point.y + 210;
        headerView.backImgView.frame = rect;
    }
}


////地点点击方法
-(void)clickTitleLabel:(UITapGestureRecognizer *)tap{
    //获取点击图片的indexRow
    UILabel *lab = (UILabel *)tap.view;
    CGPoint point = lab.center;
    point = [_tableView convertPoint:point fromView:lab.superview];
    NSIndexPath *index = [_tableView indexPathForRowAtPoint:point];
    XYJLXResultViewController *VC = [[XYJLXResultViewController alloc] init];
    XYJXCResultFrameModel *frameModel = _dataSectionArr[index.section][index.row];
    VC.selfID = frameModel.model.entry_id;
    if (![VC.selfID isEqualToString:@""]) {
        [self.navigationController pushViewController:VC animated:YES];
    }
}


//图片的点击方法
-(void)click:(UITapGestureRecognizer *)tap{
    NSLog(@"点击图片");
    //获取点击图片的indexRow
    UIImageView *img = (UIImageView *)tap.view;
    CGPoint point = img.center;
    point = [_tableView convertPoint:point fromView:img.superview];
    _indexPath = [_tableView indexPathForRowAtPoint:point];
    //获取每个section的图片数量
    NSInteger imageCount = [_dataUrlArrSection[_indexPath.section] count];
    // 快速创建并进入浏览模式
    XLPhotoBrowser * browser = [XLPhotoBrowser showPhotoBrowserWithCurrentImageIndex:_indexPath.row-1 imageCount:imageCount datasource:self];
    //影藏小圆点
    browser.showPageControl = NO;
    browser.pageControlStyle = XLPhotoBrowserPageControlStyleNone;
    // 设置长按手势弹出的地步ActionSheet数据,不实现此方法则没有长按手势
    [browser setActionSheetWithTitle:@"" delegate:self cancelButtonTitle:@"取消" deleteButtonTitle:nil otherButtonTitles:@"保存图片",@"发送给朋友",nil];
    
    // 自定义一些属性
    browser.pageDotColor = [UIColor purpleColor]; ///< 此属性针对动画样式的pagecontrol无效
    browser.currentPageDotColor = [UIColor greenColor];
    //browser.pageControlStyle = XLPhotoBrowserPageControlStyleAnimated;///< 修改底部pagecontrol的样式为系统样式,默认是弹性动画的样式
}



#pragma mark    -   XLPhotoBrowserDatasource

/**
 *  返回这个位置的占位图片 , 也可以是原图(如果不实现此方法,会默认使用placeholderImage)
 *
 *  @param browser 浏览器
 *  @param index   位置索引
 *
 *  @return 占位图片
 */
- (UIImage *)photoBrowser:(XLPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index
{
    return nil;
}

/**
 *  返回指定位置图片的UIImageView,用于做图片浏览器弹出放大和消失回缩动画等
 *  如果没有实现这个方法,没有回缩动画,如果传过来的view不正确,可能会影响回缩动画效果
 *
 *  @param browser 浏览器
 *  @param index   位置索引
 *
 *  @return 展示图片的容器视图,如UIImageView等
 */
- (UIView *)photoBrowser:(XLPhotoBrowser *)browser sourceImageViewForIndex:(NSInteger)index
{
    //返回指定位置
    [self returnTabelViewCellWithIndex:index];
    return _dataImageViewArray[_indexPath.section][index];
}


- (void)returnTabelViewCellWithIndex:(NSInteger)index{
    
    NSLog(@"点击图片消失");
    NSIndexPath * selfIndexPath = [NSIndexPath indexPathForRow:index+1 inSection:_indexPath.section];
    [_tableView scrollToRowAtIndexPath:selfIndexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

/**
 *  返回指定位置的高清图片URL
 *
 *  @param browser 浏览器
 *  @param index   位置索引
 *
 *  @return 返回高清大图索引
 */
- (NSURL *)photoBrowser:(XLPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index
{
    return [NSURL URLWithString:_dataUrlArrSection[_indexPath.section][index]];
}


#pragma mark    -   XLPhotoBrowserDelegate

- (void)photoBrowser:(XLPhotoBrowser *)browser clickActionSheetIndex:(NSInteger)actionSheetindex currentImageIndex:(NSInteger)currentImageIndex
{
    switch (actionSheetindex) {
            
        case 0: // 保存
        {
            NSLog(@"点击了actionSheet索引是:%zd , 当前展示的图片索引是:%zd",actionSheetindex,currentImageIndex);
            [browser saveCurrentShowImage];
        }
            break;
        case 1: // 收藏
        {
            NSLog(@"点击了actionSheet索引是:%zd , 当前展示的图片索引是:%zd",actionSheetindex,currentImageIndex);
            NSLog(@"点击收藏");
            [self shareIconToWechat:currentImageIndex];
        }
            break;
        default:
        {
            NSLog(@"点击了actionSheet索引是:%zd , 当前展示的图片索引是:%zd",actionSheetindex,currentImageIndex);
        }
            break;
    }
}

#pragma mark - 分享

//分享网络连接
- (void)shareWebToWechat{
    
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    //url转换成NSData（如果直接使用无法获取）
    NSString *urlString = imageUrl;
    NSData *data = [NSData dataWithContentsOfURL:[NSURL  URLWithString:urlString]];
    //创建网页内容对象
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:[NSString stringWithFormat:@"鹿林推荐精选行程行程:%@",name] descr:@"LLlianxi" thumImage:[UIImage imageWithData:data]];
    //设置网页地址
    
    shareObject.webpageUrl = [NSString stringWithFormat:@"http://chanyouji.com/plans/%@?from=groupmessage&isappinstalled=1",_selfID];
    
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:UMSocialPlatformType_WechatSession messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            NSLog(@"************Share fail with error %@*********",error);
        }else{
            NSLog(@"response data is %@",data);
        }
    }];
}


//分享图片连接
- (void)shareIconToWechat:(NSInteger)currentImageIndex{
    
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    
    //创建图片内容对象
    UMShareImageObject *shareObject = [[UMShareImageObject alloc] init];
    //如果有缩略图，则设置缩略图
    [shareObject setShareImage:[_dataImageViewArray[currentImageIndex] image]];
    
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:UMSocialPlatformType_WechatSession messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            NSLog(@"************Share fail with error %@*********",error);
        }else{
            NSLog(@"response data is %@",data);
        }
    }];
}


@end
